package godau.fynn.bandcampdirect.activity.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import godau.fynn.bandcampdirect.R;
import godau.fynn.bandcampdirect.SharedPreferences;

public class LoginFragment extends Fragment {

    public static final String LOGIN_URL = "https://bandcamp.com/login";

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.content_webview, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {

        WebView webView = view.findViewById(R.id.webview);

        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        CookieManager cookieMan = CookieManager.getInstance();
        cookieMan.removeAllCookies(aBoolean -> webView.loadUrl(LOGIN_URL));

        webView.setWebViewClient(new WebViewClient() {

            @Override
            public void onLoadResource(WebView view, String url) {

                testIdentityCookie();

                super.onLoadResource(view, url);
            }

            @Override
            public void onPageFinished(WebView view, String url) {

                testIdentityCookie();

                super.onPageFinished(view, url);
            }

            private void testIdentityCookie() {
                String cookies = CookieManager.getInstance().getCookie("https://bandcamp.com");

                if (cookies != null && cookies.contains("identity")) {
                    String[] cookiesSeparated = cookies.split("; ");
                    for (String cookie :
                            cookiesSeparated) {
                        String[] cookieData = cookie.split("=");
                        if (cookieData[0].equals("identity")) {

                            // Identity was found
                            String identity = cookieData[1];
                            new SharedPreferences(webView.getContext()).edit()
                                    .putString(SharedPreferences.IDENTITY_TOKEN, identity).apply();

                            if (getActivity() != null) {
                                getActivity()
                                        .getSupportFragmentManager()
                                        .popBackStack();
                                webView.stopLoading();
                            }

                        }
                    }
                }
            }

        });
    }
}
